package com_github_lib_base.view.rv

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

class MultiTypeAdapter<T : Any>(private val context: Context) :
    RecyclerView.Adapter<BaseViewHolder<*>>() {

    // 注册的布局类型列表
    private val itemTypes = mutableListOf<ItemType<in T, *>>()

    // 数据集合
    private var items: MutableList<T> = mutableListOf()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*> {
        val inflater = LayoutInflater.from(context)
        val itemType = itemTypes[viewType]
        val binding = itemType.layoutInflater(inflater, parent)
        return BaseViewHolder(binding)
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) {
        val item = items[position]
        val itemType = itemTypes[holder.itemViewType]
        @Suppress("UNCHECKED_CAST")
        (itemType.binder as ItemBinder<T, ViewDataBinding>).bind(
            item,
            holder.binding as ViewDataBinding,
            position
        )
    }

    override fun getItemViewType(position: Int): Int {
        val item = items[position]
        return itemTypes.indexOfFirst { it.matcher(item) }
    }

    fun addModels(newItems: MutableList<T>) {
        items = newItems
        notifyDataSetChanged()
    }

    // DSL注册函数
    fun registerType(block: ItemTypeBuilder<T>.() -> Unit) {
        val builder = ItemTypeBuilder<T>().apply(block)
        itemTypes.add(builder.build())
    }
}

// DSL扩展函数
fun <T : Any> RecyclerView.multiTypeAdapter(
    context: Context = this.context,
    block: MultiTypeAdapter<T>.() -> Unit
): MultiTypeAdapter<T> {
    return MultiTypeAdapter<T>(context).apply(block).also {
        adapter = it
    }
}

// 扩展函数实现
/*
fun <T : Any> RecyclerView.addModels(list:  MutableList<T>) {
    (this.adapter  as MultiTypeAdapter<T>).addModels(list)
}*/
